package com.gmrz.uap.equipment;

import com.gmrz.uap.cache.AmmsCacheUtil;
import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.ConditionConst;
import com.gmrz.uap.common.ControllerSupport;
import com.gmrz.uap.common.DBCommon;
import com.gmrz.uap.model.*;
import com.gmrz.uap.operlog.OperLogService;
import com.gmrz.uap.resource.ResourceInterceptor;
import com.gmrz.uap.tenant.TenantService;
import com.gmrz.uap.util.Identities;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class EquipmentController extends ControllerSupport {

    private final static Logger LOG = Logger.getLogger(EquipmentController.class);

    @Before(ResourceInterceptor.class)
    public void index() {

    }

    //厂商管理
    public void vendor() {

    }

    //获取厂商列表信息
    public void vendorList() {
        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, "vendor_name");
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        Vendor vendor = getModel(Vendor.class);

        Page<Vendor> descPage = EquipmentService.me.findVendorListForPaginate(vendor, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, descPage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, descPage.getList());

        render(responseJsonRender(result));
    }


    public void findVendorListForPaginateNotInAllow() {
        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, "vendor_name");
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        Vendor vendor = getModel(Vendor.class);
        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);
        Page<Vendor> descPage = EquipmentService.me.findVendorListForPaginateNotInAllow(vendor, tenantId, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, descPage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, descPage.getList());

        render(responseJsonRender(result));
    }


    public void findVendorAllowListForPaginate() {
        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, "vendor_name");
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        VendorAllow vendorAllow = getModel(VendorAllow.class);

        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);
        vendorAllow.setTenantId(tenantId);

        Page<VendorAllow> descPage = EquipmentService.me.findVendorAllowListForPaginate(vendorAllow, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, descPage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, descPage.getList());

        render(responseJsonRender(result));
    }

    //增加厂商
    public void vendorAdd() {
        render("vendorForm" + SystemConst.VIEW_EXTENDSION);
    }



    public void vendorSave() {
        Vendor vendor = getModel(Vendor.class);

        flag = EquipmentService.me.vendorExist(vendor.getVendorName());

        if (flag) {
            flag = false;
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, "厂商名称已经存在，请重新输入");
            render(responseJsonRender(result));
            return;
        }
        vendor.setVenId(Identities.uuid2());
        flag = vendor.save();

        LOG.debug("厂商是否新增成功？ " + flag);

        if (flag) {
            message = "厂商增加成功";
            clearVendorCache(message);
        } else {
            message = "厂商增加失败，请重试！";
        }

        LOG.debug("厂商的message： " + message);

        //增加系统操作日志
        OperLogService.me.addOperLog("增加厂商", vendor.getVendorName(), flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    //编辑厂商
    public void vendorEdit() {
        String venId = getPara();
        Vendor vendor = Vendor.dao.findById(venId);
        setAttr("vendor", vendor);
        render("vendorForm" + SystemConst.VIEW_EXTENDSION);
    }

    public void vendorUpdate() {
        Vendor vendor = getModel(Vendor.class);
        flag = EquipmentService.me.vendorIfExistForibAllow(vendor.getVenId(), getCookie(SystemConst.COOKIE_TENANT_ID));

        if (flag){
            flag = false;
            flag = vendor.update();

            if (flag) {
                message = "厂商编辑成功";
                clearVendorCache(message);
            } else {
                message = "厂商编辑失败，请重试！";
            }
        }else {
            message = "禁止此厂商编辑，已有其它渠道在使用！";
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("编辑产商", vendor.getVendorName(), flag, message, getRequest());


        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    //删除厂商
    public void vendorRemove() {
        String ids = getPara("venId");
        String vendorNames = getPara("vendorName");


        String[] idArr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
        String[] vendorNameArr = vendorNames.split(SystemConst._DEFAULT_SEPARATOR_COMMA);

        StringBuilder isUseVendor = new StringBuilder();
        for (int i = 0; i < idArr.length; i++) {
            boolean isUse = EquipmentService.me.checkVendorIsUse(idArr[i]);
            if (isUse) {
                isUseVendor.append(vendorNameArr[i]).append(SystemConst._DEFAULT_SEPARATOR_COMMA);
            }
        }

        //判断厂商是否被使用，如果被使用则返回，并给出提示不能删除已经使用的厂商
        if (StringUtils.isNotBlank(isUseVendor)) {
            message = isUseVendor + "已经被使用，不能删除！";
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }

        flag = EquipmentService.me.vendorRemove(ids);

        if (flag) {
            message = "删除厂商成功！";
            clearVendorCache(message);
        } else {
            message = "删除厂商失败，请重试！";
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("删除厂商", vendorNames, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    public void findVendorList() {
        List<Vendor> vendorList = EquipmentService.me.findVendorList();
        render(responseJsonRender(vendorList));
    }

    public void list() {
        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, "equ_model");
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        Equipment equipment = getModel(Equipment.class);

        Page<Equipment> descPage = EquipmentService.me.findEquipmentListForPaginate(equipment, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, descPage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, descPage.getList());

        render(responseJsonRender(result));
    }


    public void add() {
        render("form" + SystemConst.VIEW_EXTENDSION);
    }


    public void save() {
        Equipment equipment = getModel(Equipment.class);

        flag = EquipmentService.me.exist(equipment.getEquModel(), equipment.getVenId());

        if (flag) {
            flag = false;
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, "设备型号已经存在，请重新输入");
            render(responseJsonRender(result));
            return;
        }
        equipment.setEquId(Identities.uuid2());
        flag = equipment.save();

        if (flag) {
            message = "设备型号增加成功";
            clearEquipmentCache(message);
        } else {
            message = "设备型号增加失败，请重试！";
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("增加设备型号", equipment.getEquModel(), flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    public void edit() {
        Equipment equipment = Equipment.dao.findById(getPara());
        setAttr("equipment", equipment);
        render("form" + SystemConst.VIEW_EXTENDSION);
    }


    public void update() {
        Equipment equipment = getModel(Equipment.class);

        flag = EquipmentService.me.equipmentIfExistForibAllow(equipment.getEquId(), getCookie(SystemConst.COOKIE_TENANT_ID));
        if (!flag) {
            flag = false;
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, "禁止此设备型号编辑，已有其它渠道使用！");
            render(responseJsonRender(result));
            return;
        }

        flag = EquipmentService.me.exist(equipment.getEquModel(), equipment.getVenId());

        if (flag) {
            flag = false;
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, "设备型号已经存在，请重新输入");
            render(responseJsonRender(result));
            return;
        }


        flag = equipment.update();

        if (flag) {
            message = "设备型号编辑成功";
            clearEquipmentCache(message);
        } else {
            message = "设备型号编辑失败，请重试！";
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("编辑设备型号", equipment.getEquModel(), flag, message, getRequest());


        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    public void remove() {
        String ids = getPara("ids");
        String equModels = getPara("equModels");


        String[] idArr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
        String[] equModelArr = equModels.split(SystemConst._DEFAULT_SEPARATOR_COMMA);

        StringBuilder isUseEquModel = new StringBuilder();
        for (int i = 0; i < idArr.length; i++) {
            boolean isUse = EquipmentService.me.checkEquipmentIsUse(idArr[i]);
            if (isUse) {
                isUseEquModel.append(equModelArr[i]).append(SystemConst._DEFAULT_SEPARATOR_COMMA);
            }
        }

        //判断厂商是否被使用，如果被使用则返回，并给出提示不能删除已经使用的厂商
        if (StringUtils.isNotBlank(isUseEquModel)) {
            message = isUseEquModel + "已经被使用，不能删除！";
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }


        flag = EquipmentService.me.remove(ids);

        if (flag) {
            message = "删除设备型号成功！";
            clearEquipmentCache(message);
        } else {
            message = "删除设备型号失败，请重试！";
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("删除设备型号", equModels, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    public void vendorAllow() {
        render("vendorAllow" + SystemConst.VIEW_EXTENDSION);
    }



    public void vendorAllowSave() {
        String venIds = getPara("venIds");
        String equIds = getPara("equIds");
        String equVerIds = getPara("equVerIds");
        String equModels = getPara("equModels");
        String equVersions = getPara("equVersions");
        String vendorNames = getPara("vendorNames");
        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);

        try {
            VendorAllow vendorAllow;
            String[] venIdArr = venIds.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
            String[] equIdArr = equIds.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
            String[] equVerIdArr = equVerIds.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
            for (int i = 0; i < venIdArr.length; i++) {

                vendorAllow = new VendorAllow();
                vendorAllow.setTenantId(tenantId);
                vendorAllow.setVenId(venIdArr[i]);
                vendorAllow.setVfId(Identities.uuid2());
                if (!ConditionConst.CONDITTION_FORBID_EQUID.equals(equIdArr[i]))
                    vendorAllow.setEquId(equIdArr[i]);
                if (!ConditionConst.CONDITTION_FORBID_EQUVERSIONID.equals(equVerIdArr[i]))
                    vendorAllow.setEquVersionId(equVerIdArr[i]);
                flag = vendorAllow.save();

                if (!flag) {
                    break;
                }
            }

            if (flag) {
                message = "增加厂商型号版本白名单成功！";
                String cacheKey = AmmsCacheUtil.CACHE_VENDOR_ALLOW + "." + tenantId;
                LOG.info("厂商型号版本白名单缓存键值 => " + cacheKey);
                message = AmmsCacheUtil.deleteIfSuccess(cacheKey, message);
            } else {
                message = "增加厂商型号版本白名单失败，请重试！";
            }

        } catch (JedisConnectionException jedisConnectionException) {
            message += getRes().get("redis.connection.failed");
            LOG.error(message, jedisConnectionException);
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("增加厂商型号版本白名单", vendorNames+" | "+equModels+" | "+equVersions, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    public void vendorAllowRemove() {
        String ids = getPara("ids");
        String vendorNames = getPara("vendorNames");
        String equModels = getPara("equModels");
        String equVersions = getPara("equVersions");
        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);

        try {
            VendorAllow vendorAllow;
            String[] idArr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
            for (int i = 0; i < idArr.length; i++) {

                vendorAllow = new VendorAllow();
                flag = vendorAllow.deleteById(idArr[i]);

                if (!flag) {
                    break;
                }
            }

            if (flag) {
                message = "删除厂商型号版本白名单成功！";
                String cacheKey = AmmsCacheUtil.CACHE_VENDOR_ALLOW + "." + tenantId;
                LOG.info("厂商型号版本白名单缓存键值 => " + cacheKey);
                message = AmmsCacheUtil.deleteIfSuccess(cacheKey, message);
            } else {
                message = "删除厂商型号版本白名单失败，请重试！";
            }
        } catch (JedisConnectionException jedisConnectionException) {
            message += getRes().get("redis.connection.failed");
            LOG.error(message, jedisConnectionException);
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("删除厂商型号版本白名单", vendorNames+" | "+equModels+" | "+equVersions, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    public void equipmentForbid() {
        render("equipmentForbid" + SystemConst.VIEW_EXTENDSION);
    }


    public void findListForPaginateNotInForbid() {
        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, "vendor_name");
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        Equipment equipment = getModel(Equipment.class);

        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);
        Page<Equipment> descPage = EquipmentService.me.findListForPaginateNotInForbid(equipment, tenantId, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, descPage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, descPage.getList());

        render(responseJsonRender(result));
    }


    public void findEquipmentForbidListForPaginate() {
        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, "vendor_name");
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        EquipmentForbid equipmentForbid = getModel(EquipmentForbid.class);
        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);
        equipmentForbid.setTenantId(tenantId);


        Page<EquipmentForbid> descPage = EquipmentService.me.findEquipmentForbidListForPaginate(equipmentForbid, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, descPage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, descPage.getList());

        render(responseJsonRender(result));
    }



    public void equipmentForbidSave() {
        String venIds = getPara("venIds");
        String equIds = getPara("equIds");
        String equVerIds = getPara("equVerIds");
        String equModels = getPara("equModels");
        String equVersions = getPara("equVersions");
        String vendorNames = getPara("vendorNames");
        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);

        try {
            EquipmentForbid equipmentForbid;
            String[] venIdArr = venIds.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
            String[] equIdArr = equIds.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
            String[] equVerIdArr = equVerIds.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
            for (int i = 0; i < venIdArr.length; i++) {

                equipmentForbid = new EquipmentForbid();
                equipmentForbid.setTenantId(tenantId);
                if (!ConditionConst.CONDITTION_FORBID_EQUID.equals(equIdArr[i]))
                    equipmentForbid.setEquId(equIdArr[i]);
                if (!ConditionConst.CONDITTION_FORBID_EQUVERSIONID.equals(equVerIdArr[i]))
                    equipmentForbid.setEquVersionId(equVerIdArr[i]);
                equipmentForbid.setVenId(venIdArr[i]);
                equipmentForbid.setEaId(Identities.uuid2());
                flag = equipmentForbid.save();

                if (!flag) {
                    break;
                }
            }

            if (flag) {
                message = "增加厂商型号版本黑名单成功！";
                String cacheKey = AmmsCacheUtil.CACHE_EQUIPMENT_FORBID + "." + tenantId;
                LOG.info("厂商型号版本黑名单缓存键值 => " + cacheKey);
                message = AmmsCacheUtil.deleteIfSuccess(cacheKey, message);
            } else {
                message = "增加厂商型号版本黑名单失败，请重试！";
            }

        } catch (JedisConnectionException jedisConnectionException) {
            message += getRes().get("redis.connection.failed");
            LOG.error(message, jedisConnectionException);
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("增加厂商型号版本黑名单", vendorNames+" | "+equModels+" | "+equVersions, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    public void equipmentForbidRemove() {
        String ids = getPara("ids");
        String vendorNames = getPara("vendorNames");
        String equModels = getPara("equModels");
        String equVersions = getPara("equVersions");
        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);

        try {
            EquipmentForbid equipmentForbid;
            String[] idArr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
            for (int i = 0; i < idArr.length; i++) {

                equipmentForbid = new EquipmentForbid();
                flag = equipmentForbid.deleteById(idArr[i]);

                if (!flag) {
                    break;
                }
            }

            if (flag) {
                message = "删除厂商型号版本黑名单成功！";
                String cacheKey = AmmsCacheUtil.CACHE_EQUIPMENT_FORBID + "." + tenantId;
                LOG.info("厂商型号版本黑名单缓存键值 => " + cacheKey);
                message = AmmsCacheUtil.deleteIfSuccess(cacheKey, "删除厂商型号版本黑名单成功！");
            } else {
                message = "删除厂商型号版本黑名单失败，请重试！";
            }
        } catch (JedisConnectionException jedisConnectionException) {
            message += getRes().get("redis.connection.failed");
            LOG.error(message, jedisConnectionException);
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("删除厂商型号版本黑名单", vendorNames+" | "+equModels+" | "+equVersions, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    /**
     * 设备ID黑名单主页
     */
    public void deviceForbid() {
        render("deviceForbid" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     * 设备ID黑名单列表
     */
    public void deviceForbidList() {
        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, DBCommon.TABLE_DEVICE_FORBID_COLUMN_DF_ID);
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        DeviceForbid deviceForbid = getModel(DeviceForbid.class);
        deviceForbid.setTenantId(getCookie(SystemConst.COOKIE_TENANT_ID));//设置渠道

        Page<DeviceForbid> descPage = EquipmentService.me.findDeviceForbidListForPaginate(deviceForbid, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, descPage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, descPage.getList());

        render(responseJsonRender(result));
    }


    public void deviceForbidAdd() {
        render("deviceForbidForm" + SystemConst.VIEW_EXTENDSION);
    }



    public void deviceForbidSave() {
        DeviceForbid deviceForbid = getModel(DeviceForbid.class);

        flag = EquipmentService.me.deviceIdExist(deviceForbid.getDeviceId(), getCookie(SystemConst.COOKIE_TENANT_ID));
        if (flag) {
            flag = false;
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, "设备ID已经存在，请重新输入");
            render(responseJsonRender(result));
            return;
        }
        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);
        deviceForbid.setTenantId(tenantId);
        deviceForbid.setDfId(Identities.uuid2());
        flag = deviceForbid.save();

        if (flag) {
            message = "设备ID增加成功";
            String cacheKey = String.format(AmmsCacheUtil.CACHE_DEVICE_FORBID, getCookie(SystemConst.COOKIE_TENANT_ID));
            LOG.info("设备ID黑名单缓存键值 => " + cacheKey);
            message = AmmsCacheUtil.deleteIfSuccess(cacheKey, message);
        } else {
            message = "设备ID增加失败，请重试！";
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("增加设备ID", deviceForbid.getDeviceId(), flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    //编辑设备标
    public void deviceForbidEdit() {
        String dfId = getPara();
        DeviceForbid deviceForbid = DeviceForbid.dao.findById(dfId);
        setAttr("deviceForbid", deviceForbid);
        render("deviceForbidForm" + SystemConst.VIEW_EXTENDSION);
    }

    public void deviceForbidUpdate() {
        DeviceForbid deviceForbid = getModel(DeviceForbid.class);

        flag = deviceForbid.update();

        if (flag) {
            message = "设备ID编辑成功";

            String cacheKey = String.format(AmmsCacheUtil.CACHE_DEVICE_FORBID, getCookie(SystemConst.COOKIE_TENANT_ID));
            LOG.info("设备ID黑名单缓存键值 => " + cacheKey);
            message = AmmsCacheUtil.deleteIfSuccess(cacheKey, message);

        } else {
            message = "设备ID编辑失败，请重试！";
        }


        //增加系统操作日志
        OperLogService.me.addOperLog("编辑设备ID", deviceForbid.getDeviceId(), flag, message, getRequest());


        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    //删除设备ID
    public void deviceForbidRemove() {
        String ids = getPara("dfIds");
        String deviceIds = getPara("deviceIds");


        flag = EquipmentService.me.deviceForbidRemove(ids);

        if (flag) {
            message = "删除设备ID成功！";

            String cacheKey = String.format(AmmsCacheUtil.CACHE_DEVICE_FORBID, getCookie(SystemConst.COOKIE_TENANT_ID));
            LOG.info("设备ID黑名单缓存键值 => " + cacheKey);
            message = AmmsCacheUtil.deleteIfSuccess(cacheKey, message);
        } else {
            message = "删除设备ID失败，请重试！";
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("删除设备ID", deviceIds, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    /**
     * 设备版本主页
     */
    public void deviceVersion() {
        render("deviceVersion" + SystemConst.VIEW_EXTENDSION);
    }

    public void getEquipments() {
        String venId = getPara("venId");
        List<Equipment> equipmentList = Equipment.dao.getEquipmentsByVenId(venId);
        render(responseJsonRender(equipmentList));
    }

    public void deviceVersionList() {
        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, "equ_model");
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        Page<Record> descPage = EquipmentService.me.deviceVersionList(page, rows, sort, order);
        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, descPage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, descPage.getList());

        render(responseJsonRender(result));
    }

    public void versionAdd() {
        List<Vendor> vendorList = EquipmentService.me.findVendorList();
        setAttr("vendorList", vendorList);
        render("versionForm" + SystemConst.VIEW_EXTENDSION);
    }

    public void versionSave() {
        String deviceName = getPara("deviceName");
        String deviceVersion = getPara("deviceVersion");
        Equipment.dao.deviceVersionSave(deviceName, deviceVersion);
        Equipment equipment = Equipment.dao.findById(deviceName);
        message = "添加成功";
        message = AmmsCacheUtil.deleteIfSuccess("uaf.cache.equipment.forbid.version." + equipment.getEquModel(), message);
        flag = true;
        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    public void versionEdit() {
        String versionId = getPara();

        Record record = Equipment.dao.getDeviceVersion(versionId);
        String equId = record.getStr("equ_id");
        Equipment equipment = Equipment.dao.getEquipmentById(equId);
        Vendor vendor = Vendor.dao.findById(equipment.getVenId());
        List<Vendor> vendorList = new ArrayList<Vendor>();
        vendorList.add(vendor);
        setAttr("vendorList", vendorList);

        List<Equipment> equipmentList = new ArrayList<Equipment>();
        equipmentList.add(equipment);
        setAttr("equipmentList", equipmentList);

        setAttr("deviceVersion", record.getStr("equ_version"));
        setAttr("equVersionId", record.getStr("equ_version_id"));
        render("versionForm" + SystemConst.VIEW_EXTENDSION);
    }

    public void versionUpdate() {

        String equVersionId = getPara("equVersionId");
        String deviceVersion = getPara("deviceVersion");

        flag = EquipmentService.me.equipmentVersionIfExistForibAllow(equVersionId, getCookie(SystemConst.COOKIE_TENANT_ID));
        if (!flag) {
            flag = false;
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, "禁止此版本编辑，已有其它渠道使用！");
            render(responseJsonRender(result));
            return;
        }

        Equipment.dao.deviceVersionUpdate(equVersionId, deviceVersion);
        Record record = Equipment.dao.getDeviceVersion(equVersionId);
        Equipment equipment = Equipment.dao.findById(record.getStr("equ_id"));
        message = "修改成功";
        message = AmmsCacheUtil.deleteIfSuccess("uaf.cache.equipment.forbid.version." + equipment.getEquModel(), message);

        flag = true;
        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    public void versionRemove() {

        String versionId = getPara("versionId");
        String deviceVersion = getPara("deviceVersion");

        String[] idArr = versionId.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
        String[] equVersionArr = deviceVersion.split(SystemConst._DEFAULT_SEPARATOR_COMMA);

        StringBuilder isUseEquModel = new StringBuilder();
        for (int i = 0; i < idArr.length; i++) {
            boolean isUse = EquipmentService.me.checkEquipmentVersionIsUse(idArr[i]);
            if (isUse) {
                isUseEquModel.append(equVersionArr[i]).append(SystemConst._DEFAULT_SEPARATOR_COMMA);
            }
        }

        //判断厂商是否被使用，如果被使用则返回，并给出提示不能删除已经使用的厂商
        if (StringUtils.isNotBlank(isUseEquModel)) {
            message = isUseEquModel + "已经被使用，不能删除！";
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }

        for (String id : idArr) {
            Record record = Equipment.dao.getDeviceVersion(id);
            Equipment.dao.deleteVersionById(id);
            Equipment equipment = Equipment.dao.findById(record.getStr("equ_id"));
            message = AmmsCacheUtil.deleteIfSuccess("uaf.cache.equipment.forbid.version." + equipment.getEquModel(), "删除成功！");

        }
        //message = "删除成功";
        flag = true;
        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    private void clearVendorCache(String messages) {
        List<Tenant> tenants = TenantService.me.getAllTenants();
        for (Tenant tenant : tenants) {
            String cacheKey = AmmsCacheUtil.CACHE_VENDOR_ALLOW + "." + tenant.getTanId();
            LOG.info("厂商白名单缓存键值 => " + cacheKey);
            message = AmmsCacheUtil.deleteIfSuccess(cacheKey, messages);
        }
    }

    private void clearEquipmentCache(String messages) {
        List<Tenant> tenants = TenantService.me.getAllTenants();
        for (Tenant tenant : tenants) {
            String cacheKey = AmmsCacheUtil.CACHE_EQUIPMENT_FORBID + "." + tenant.getTanId();
            LOG.info("设备型号黑名单缓存键值 => " + cacheKey);
            message = AmmsCacheUtil.deleteIfSuccess(cacheKey, messages);
        }
    }
}
